﻿using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ServiceKit.WebApi
{
    public class DynamicApiControllerFeatureProvider : ControllerFeatureProvider
    {
        public new void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature)
        {
            foreach (var part in parts.OfType<IApplicationPartTypeProvider>())
            {
                foreach (var type in part.Types)
                {
                    if (IsController(type) && !feature.Controllers.Contains(type))
                    {
                        feature.Controllers.Add(type);
                    }
                }
            }
        }

        protected override bool IsController(TypeInfo typeInfo)
        {
            var isController = base.IsController(typeInfo);
            if (!isController)
            {
                if (typeInfo.IsGenericType && typeInfo == typeof(DynamicApiController<>).GetTypeInfo())
                    isController = true;
            }
            return isController;
        }
    }
}
